using UnityEngine;

namespace FutureCorePlugin
{
    public class SafeAreaAdaptive : MonoBehaviour
    {
        [SerializeField]
        private Rect safeAreaAnchors;

        private RectTransform rectTF;

        private void Awake()
        {
            rectTF = GetComponent<RectTransform>();
            safeAreaAnchors = UIUtils.GetUISafeAreaAnchors();
            Adaptive();
        }

#if UNITY_EDITOR
        private float currScreenHeight;
        private float currScreenWidth;

        private void Update()
        {
            if (currScreenHeight != Screen.height || currScreenWidth != Screen.width)
            {
                currScreenHeight = Screen.height;
                currScreenWidth = Screen.width;
                AdaptiveConst.CurrAspectRatio = (float)Screen.height / Screen.width;
                Adaptive();
            }
        }

        private void OnValidate()
        {
            Adaptive();
        }
#endif

        private void Adaptive()
        {
            if (rectTF == null) return;

            UIUtils.SetUIFullScreen(rectTF);

            float left, bottom, right, top;
            left = safeAreaAnchors.x;
            bottom = safeAreaAnchors.y;
            right = safeAreaAnchors.width;
            top = safeAreaAnchors.height;

            rectTF.offsetMin = new Vector2(left, bottom);
            rectTF.offsetMax = new Vector2(-right, -top);
        }
    }
}